package myServlet;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import myMapper.userMapper;

/**
 * Servlet implementation class signupServlet
 */
@WebServlet("/signupServlet")
public class signupServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public signupServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		String username=request.getParameter("signupUsername");
		String password=request.getParameter("signupPassword");
		String tel=request.getParameter("signupTel");
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession sqlsession=sqlSessionFactory.openSession();
		
		userMapper mapper=sqlsession.getMapper(userMapper.class);
		if(username.length()>=2 && username.length()<13) {
			if(password.length()>=6 && password.length()<13) {
				if(tel.length()==11) {
					request.getRequestDispatcher("JSP/message.jsp?content=注册成功，请登录&href=JSP/index.jsp").forward(request, response);
				}else {
					request.getRequestDispatcher("JSP/message.jsp?content=手机号码长度必须为11位&href=JSP/index.jsp").forward(request, response);
				}
			}else {
				request.getRequestDispatcher("JSP/message.jsp?content=密码必须为6-12位&href=JSP/index.jsp").forward(request, response);
			}
		}else {
			request.getRequestDispatcher("JSP/message.jsp?content=用户名必须为2-12位&href=JSP/index.jsp").forward(request, response);
		}
		String identity="用户";
		mapper.insertAccount(username, password, tel,identity);
		sqlsession.commit();
		sqlsession.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
